var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    show7:false,
    show6:false,
    language: '',
    goodsrange: [],
    fenleirange: [],
    category: [],
    goods: [],
    sousuoInfoAllOIs:[],
    sousuoInfoSearch:[],
    goodsSelect: [], // vant自带的所选择商品的信息
    fenleiSelect: [], // vant自带的所选择分类的信息
    sousuoInfo: [], // 分类搜索返回的信息
    goodsSousuo: [], // 商品搜索返回信息
    keyword: '', // 分类搜索关键字
    goodsKeyword: '', // 商品搜索关键字
    show3: false, // 添加商品弹窗
    show1: false, // 控制会员等级弹窗的显示影藏
    show2: false, // 控制添加分类弹窗的显示影藏
    status: true, // 判断是否开启，默认开启
    is_complex: '0', // 判断单张还是多张使用，默认单张
    level_limit: '-1', // 会员等级id,默认为-1，所有会员
    coupon_method: '1', // 判断打折还立减，默认立减
    display_order: '', // 判断排序方式
    enough: '', // 订单金额限制条件
    use_type: '5', // 判断适用范围
    get_type: '1', // 判断是否可以领取
    name: '', // 优惠券名称
    deduct: '', // 立减多少元
    discount: '', // 打多少折
    time_days: '', // 选择有效天数
    time_start: '', // 选择时间范围
    time_end: '', // 选择时间范围
    dataInfo: {}, // 优惠券
    get_max: 1, // 每人限领取张数
    total: 1, // 总发放数
    onceTotal:'',//每人每日领取数量
    id: '', // 优惠券id,
    Id: '', //
    Vip: [], // 会员等级
    chooseVip: '所有会员', // 所选的会员等级名称
    time_limit: '0', // 默认选择有效天数按钮
    show4: false,
    show5: false,
    checked: false,
    time_startTimes: '',
    time_endTimes: '',
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      } else if (type === 'month') {
        return `${value}月`;
      }else if(type==='day'){
        return `${value}日`;
      }
      return value;
    },
    minDate:new Date().getTime(),

    sendBtnFlag:false,//防止多次发送
  // currentDate: new Date().getTime()
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      time_start:this.format(new Date().getTime()),
      time_end: this.format(new Date().getTime()),
    });
    if (this.options.id === undefined) {
      wx.navigateBack({
        delta: 1
      });
    }else if (this.options.id === 'abc') {
      this.getData();
      wx.setNavigationBarTitle({
        title: '优惠券发布'
      });
      this.setData({
        Id: options.id
      });
    } else {
      wx.setNavigationBarTitle({
        title: '优惠券编辑'
      });

      this.setData({
        id: options.id
      });
      this.getData();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync('langIndex');
    this.setData({ 'language': language.en});
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  timestampToTime(timestamp) {
    var date = new Date(timestamp * 1000); // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
    let Y = date.getFullYear() + '-';
    let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    let D = this.change(date.getDate()) + ' ';
    let h = this.change(date.getHours()) + ':';
    let m = this.change(date.getMinutes());
    return Y + M + D + h + m;
  },
  change(t) {
    if (t < 10) {
      return '0' + t;
    } else {
      return t;
    }
  },
  tapshowRange(){
    this.setData({show7:true})
  },
  getData() {
    let urlStr = app.getNetAddresss('plugin.store-cashier.frontend.store.center.coupon.edit');
    urlStr += '&id=' + this.data.id;
    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        var response = resdata.data;

        if (response.result == 1) {
          if (this.data.id) {
            let _status = false;
            if(response.data.status == 1){
              _status = true
            }
            this.setData({
              dataInfo: response.data,
              status: _status,
              is_complex: String(response.data.is_complex),
              coupon_method: String(response.data.coupon_method),
              use_type: String(response.data.use_type),
              get_type: String(response.data.get_type),
              level_limit: String(response.data.level_limit),
              enough: response.data.enough,
              display_order: response.data.display_order,
              name: response.data.name,
              time_limit: String(response.data.time_limit),
              onceTotal:response.data.get_limit_max
            });

            if (response.data.time_limit == 0) {
              this.setData({
                time_days: response.data.time_days
              });
            }
            if (response.data.time_limit == 1) {
              this.setData({
                time_start: this.timestampToTime(response.data.time_start),
                time_end: this.timestampToTime(response.data.time_end)
              });
              let time_start = new Date(this.data.time_start);
              time_start = time_start.getTime();

              let time_end = new Date(this.data.time_end);
              time_end = time_end.getTime();
              this.setData({
                time_startTimes: time_start,
                time_endTimes: time_end
              });
            }
            if (this.data.coupon_method == 1) {
              this.setData({
                deduct: response.data.deduct
              });
            }
            if (this.data.coupon_method == 2) {
              this.setData({
                discount: response.data.discount
              });
            }
            if (this.data.use_type == 1) {
              this.setData({
                category: response.data.category
              });
            }
            if (this.data.use_type == 2) {
              this.setData({
                goods: response.data.goods
              });
            }
            this.setData({
              Vip: response.data.memberLevels,
              get_max: response.data.get_max,
              total: response.data.total
            });
            for (let i = 0;i < this.data.Vip.length;i++) {
              if (response.data.level_limit == this.data.Vip[i].id) {
                this.setData({
                  chooseVip: `${this.data.Vip[i].level_name}`
                });
              }
            }
          } else {
            this.setData({
              Vip: response.data.memberLevels
            });
          }
        }else if (response.result === 0) {
          if (response.data.url) {
            // window.location.href=response.data.url
          } else {
            wx.showToast({
              title: response.msg,
              icon: 'none'
            });
          }
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  // 发布中选中的分类的删除方法
  classifyDelete(e) {
    let item = e.target.dataset.item || e.currentTarget.dataset.item;
    let fenleirange = this.data.fenleirange;

    for (let i = 0;i < fenleirange.length;i++) {
      if (item.id == fenleirange[i].id) {
        fenleirange.splice(i, 1);
      }
    }
    this.setData({
      fenleirange});
  },
  // 发布中选中的商品的删除方法
  goodsDelete(e) {
    let items = e.target.dataset.item || e.currentTarget.dataset.item;
    let goodsrange = this.data.goodsrange;
    for (let i = 0;i < goodsrange.length;i++) {
      if (items.id == goodsrange[i].id) {
        goodsrange.splice(i, 1);
      }
    }
    this.setData({
      goodsrange});
  },
  // 编辑中选中的分类的删除方法
  classifyDDelete(e) {
    let itemIfy = e.target.dataset.item || e.currentTarget.dataset.item;
    let category = this.data.category;
    for (let i = 0; i < category.length; i++) {
      if (itemIfy.id == category[i].id) {
        category.splice(i, 1);
      }
    }
    this.setData({
      category});
  },
  // 编辑中选中的商品的删除方法
  goodsDDelete(e) {
    let itemgoos = e.target.dataset.item || e.currentTarget.dataset.item;
    let goods = this.data.goods;
    for (let i = 0;i < goods.length;i++) {
      if (itemgoos.id == goods[i].id) {
        goods.splice(i, 1);
      }
    }
    this.setData({
      goods});
  },
  // 初始化搜索框内容和搜索数据
  inniClassify() {
    this.setData({
      show2: true,
      sousuoInfo: [],
      keyword: ''
    });
  },
  inniGoods() {
    this.setData({
      show3: true,
      goodsSousuo: [],
      goodsKeyword: ''
    });
  },
  // 关闭会员等级弹窗
  close() {
    this.setData({
      show1: false
    });
  },
  // 关闭分类搜索弹窗
  closeClassify() {
    this.setData({
      show2: false,
      fenleiSelect: []
    });
  },
  // 关闭商品搜索弹窗
  closeGoods() {
    this.setData({
      show3: false,
      goodsSelect: []
    });
  },
  //
  // 分类搜索选中分类后方法
  finishClassify() {
    let newArr = this.data.fenleiSelect;
    let oldArr = this.data.sousuoInfoAllOIs;
    let arrIOs = this.data.fenleirange;

    oldArr.map(item => {
      for (var i = 0; i < newArr.length; i++) {
        if (item.name == newArr[i]) {
          arrIOs.push(item);
        }
      }
    });

    this.setData({
      show2: false,
      fenleirange: arrIOs,
      fenleiSelect: []
    });
  },
  finishcategory() {
    let arrAll = this.data.sousuoInfoSearch;
    let arrChe = this.data.fenleiSelect;
    let arrNow = this.data.category;
    arrAll.map(item => {
      for (var i = 0; i < arrChe.length; i++) {
        if (item.name == arrChe[i]) {
          arrNow.push(item);
        }
      }
    });

    this.setData({
      show2: false,
      category: arrNow,
      fenleiSelect: []
    });
  },
  // 判断数组是否存在某一因素
  deteleObject(obj) {
    var uniques = [];
    var stringify = {};
    for (var i = 0; i < obj.length; i++) {
      var keys = Object.keys(obj[i]);
      keys.sort(function (a, b) {
        return (Number(a) - Number(b));
      });
      var str = '';
      for (var j = 0; j < keys.length; j++) {
        str += JSON.stringify(keys[j]);
        str += JSON.stringify(obj[i][keys[j]]);
      }
      if (!stringify.hasOwnProperty(str)) {
        uniques.push(obj[i]);
        stringify[str] = true;
      }
    }
    return uniques;
  },
  // 找出两个数组不同的元素

  // 发布时分类弹窗搜索按钮方法
  ClassifySousuo() {
    // if (app._isTextEmpty(this.data.keyword)) {
    //   wx.showToast({
    //     title: '请输入搜索内容',
    //     icon: 'none'
    //   });
    // }else {
      let json = {
        keyword: this.data.keyword
      };
      let urlStr = app.getNetAddresss('plugin.store-cashier.frontend.store.center.coupon.getSearchCategories');
      app._postNetWork({
        url: urlStr,
        data: json,
        success: (resdata) => {
          var response = resdata.data;
          if (response.result == 1) {
            let data = response.data;
            let cateArr = [];
            let newArr = [];
            if(this.data.Id=='abc'){
              cateArr = this.data.fenleirange;
              this.setData({sousuoInfoAllOIs: response.data})
            }else{
              cateArr = this.data.category;
              this.setData({sousuoInfoSearch: response.data})
            }
            if (cateArr.length > 0) {
              let ids = [];
              cateArr.forEach(i => {
                ids.push(i.id);
              });
              newArr = data.filter(item => {
                return ids.indexOf(item.id) == -1;
              });
            }

            if (cateArr.length == 0) {
              newArr = data;
            }
            this.setData({sousuoInfo: newArr});

          } else if (response.result === 0) {
            if (response.data.url) {
              // window.location.href = response.data.url
            }
          } else {
            wx.showToast({
              title: response.msg,
              icon: 'none'
            });
          }
        },
        fail: function (res) {
          console.log(res);
        }
      });
    // }
  },


  // 发布时商品弹窗搜索按钮方法
  goodsousuo() {
    // if (app._isTextEmpty(this.data.goodsKeyword)) {
    //   wx.showToast({
    //     title: '请输入搜索内容',
    //     icon: 'none'
    //   });
    // }else {
      let json = {
        keyword: this.data.goodsKeyword
      };
      let urlStr = app.getNetAddresss('plugin.store-cashier.frontend.store.center.coupon.getSearchGoods');
      app._postNetWork({
        url: urlStr,
        data: json,
        success: (resdata) => {
          var response = resdata.data;

          if (response.result == 1) {
            let goods = [];

            if(this.data.Id=='abc'){
              goods = this.data.goodsrange;
            }else{
              goods = this.data.goods;
            }
            let goodsAll = response.data;
            let newGoods = [];
            if (goods.length > 0) {
              let ids = [];
              goods.forEach(i => {
                ids.push(i.id);
              });
              newGoods = goodsAll.filter(item => {
                return ids.indexOf(item.id) == -1;
              });
            } else if (goods.length <= 0) {
              newGoods = goodsAll;
            }

            this.setData({
              goodsSousuo: newGoods,
              goodSousuoAll: response.data,
              goodsSousuoAll:response.data
            });
          } else if (response.result === 0) {
            if (response.data.url) {
              // window.location.href = response.data.url
            }
          } else {
            wx.showToast({
              title: response.msg,
              icon: 'none'
            });
          }
        },
        fail: function (res) {
          console.log(res);
        }
      });

    // }
  },
  // 选择等级完成的回调
  finish() {
    this.setData({
      show1: false
    });
    if (this.data.level_limit == -1) {
      this.setData({
        chooseVip: '所有会员'
      });
    }else {
      for (let i = 0;i < this.data.Vip.length;i++) {
        if (this.data.level_limit == this.data.Vip[i].id) {
          this.setData({
            chooseVip: `${this.data.Vip[i].level_name}`
          });
        }
      }
    }
  },
  // 发布优惠券
  publishInfo() {
    if(this.data.sendBtnFlag==true)return;
    if (app._isTextEmpty(this.data.display_order) || isNaN(this.data.display_order)) {
      wx.showToast({
        title: '请输入排序方法，必须是整数',
        icon: 'none'
      });
      return;
    }
    // if (app._isTextEmpty(this.data.onceTotal)) {
    //   wx.showToast({
    //     title: '请输入每人每日限领数量',
    //     icon: 'none'
    //   });
    //   return;
    // }
    if (app._isTextEmpty(this.data.name)) {
      wx.showToast({
        title: '请输入优惠券名称',
        icon: 'none'
      });
      return;
    }
    if (app._isTextEmpty(this.data.enough) || isNaN(this.data.enough)) {
      wx.showToast({
        title: '请输入订单金额,必须是整数',
        icon: 'none'
      });
      return;
    }
    if (this.data.time_limit == 0) {
      if (app._isTextEmpty(this.data.time_days)) {
        wx.showToast({
          title: '请输入有效天数',
          icon: 'none'
        });
        return;
      }
    }
    // if (this.data.time_limit == 1) {
    //   if (app.isIosOrAndroid() == 'android') {
    //     if (new Date(this.data.time_start).getTime() >= new Date(this.data.time_end).getTime()) {
    //       wx.showToast({
    //         title: '开始时间必须早于结束时间',
    //         icon: 'none'
    //       });
    //       return;
    //     }
    //   }else {
    //     if (parseInt(Date.parse(new Date(this.data.time_start.replace(/-/g, '/')))) >= parseInt(Date.parse(new Date(this.data.time_end.replace(/-/g, '/'))))) {
    //       wx.showToast({
    //         title: '开始时间必须早于结束时间',
    //         icon: 'none'
    //       });
    //       return;
    //     }
    //   }
    // }
    if (this.data.coupon_method === 1) {
      if (app._isTextEmpty(this.deduct)) {
        wx.showToast({
          title: '请输入立减金额',
          icon: 'none'
        });
        return;
      }
      else if (Number(this.data.deduct < 1)) {
        wx.showToast({
          title: '金额必须大于1',
          icon: 'none'
        });
        return;
      }
      else if (Number(this.data.deduct) > Number(this.data.enough)) {
        let between = `输入的金额必须介于1-${this.data.enough}之间`;
        wx.showToast({
          title: between,
          icon: 'none'
        });
        return;
      }
    }
    if (this.data.coupon_method === 2) {
      if (app._isTextEmpty(this.data.discount)) {
        wx.showToast({
          title: '请输入折扣数',
          icon: 'none'
        });
        return;
      }
      else if (Number(this.data.discount < 1) || Number(this.data.discount >= 10)) {
        let Between = `折扣数必须介于1-9之间`;
        wx.showToast({
          title: Between,
          icon: 'none'
        });
        return;
      }
    }
    if (this.data.use_type === 1) {
      if (this.data.fenleirange.length <= 0) {
        wx.showToast({
          title: '分类不能为空',
          icon: 'none'
        });
        return;
      }
    }
    if (this.data.use_type === 2) {
      if (this.data.goodsrange.length <= 0) {
        wx.showToast({
          title: '商品不能为空',
          icon: 'none'
        });
        return;
      }
    }
    if (this.data.get_type === 1) {
      if (app._isTextEmpty(this.data.get_max)) {
        wx.showToast({
          title: '请输入限领张数',
          icon: 'none'
        });
        return;
      } else if (app._isTextEmpty(this.data.total)) {
        wx.showToast({
          title: '请输入发放总数',
          icon: 'none'
        });
        return;
      }
    }
    if (this.data.get_type === 0) {
      if (app._isTextEmpty(this.data.total)) {
        wx.showToast({
          title: '请输入发放总数',
          icon: 'none'
        });
        return;
      }
    }
    this.data.sendBtnFlag = true;
    let time_start = new Date(this.data.time_start.replace(/-/g, '/'));
    time_start = time_start.getTime() / 1000;
    let time_end = new Date(this.data.time_end.replace(/-/g, '/'));
    time_end = time_end.getTime() / 1000;
    let allArr = this.data.goodSousuoAll;
    let xuanArr = this.data.goodsrange;
    let newArr = [];
    if (this.data.use_type == '2') {
      allArr.map(item => {
        for (var i = 0; i < xuanArr.length; i++) {
          if (item.id == xuanArr[i].id) {
            newArr.push(item);
          }
        }
      });
    }

    let _status = this.data.status ? 1 : 0;
    let json = {coupon: {
      name: this.data.name,
      get_type: this.data.get_type,
      level_limit: this.data.level_limit,
      use_type: this.data.use_type,
      enough: this.data.enough,
      time_limit: this.data.time_limit,
      time_days: this.data.time_days,
      time_start: time_start,
      time_end: time_end,
      coupon_method: this.data.coupon_method,
      discount: this.data.discount,
      deduct: this.data.deduct,
      total: this.data.total,
      status: _status,
      display_order: this.data.display_order,
      is_complex: this.data.is_complex,
      get_max: this.data.get_max,
      category: this.data.fenleirange,
      goods: newArr,
      get_limit_max:this.data.onceTotal?this.data.onceTotal:0
    }
    };
    if (this.data.use_type == '1') {
      json.coupon.goods = [];
    } else if (this.data.use_type == '2') {
      json.coupon.category = [];
    }
    let urlStr = app.getNetAddresss('plugin.store-cashier.frontend.store.center.coupon.save');
    app._postNetWork({
      url: urlStr,
      data: json,

      success: (resdata) => {
        var response = resdata.data;

        if (response.result == 1) {
          wx.showToast({
            title: '发布成功'
          });
          setTimeout(() => {
            wx.navigateBack({
              delta: 1
            });
          }, 2000);
        } else if (response.result === 0) {
          if (response.data.url) {
            // window.location.href=response.data.url
          } else {
            if(response.msg.enough){
              wx.showToast({
                title:response.msg.deduct[0],
                icon: 'none'
              });
            }else{
              wx.showToast({
                title: response.msg ,
                icon: 'none'
              });
            }

          }
          this.data.sendBtnFlag = false;
        }
      },
      fail: (res)=> {
        this.data.sendBtnFlag = false;
        console.log(res);
      }
    });
  },
  // 编辑优惠券
  editInfo() {
    if(this.data.sendBtnFlag==true)return;
    if (app._isTextEmpty(this.data.display_order) || isNaN(this.data.display_order)) {
      wx.showToast({
        title: '请输入排序方法，必须是整数',
        icon: 'none'
      });
      return;
    }
    if (app._isTextEmpty(this.data.name)) {
      wx.showToast({
        title: '请输入优惠券名称',
        icon: 'none'
      });
      return;
    }
    if (app._isTextEmpty(this.data.enough) || isNaN(this.data.enough)) {
      wx.showToast({
        title: '请输入订单金额,必须是整数',
        icon: 'none'
      });
      return;
    }
    if (this.data.time_limit == 0) {
      if (app._isTextEmpty(this.data.time_days)) {
        wx.showToast({
          title: '请输入有效天数',
          icon: 'none'
        });
        return;
      }
    }
    // if (this.data.time_limit == 1) {
    //   if (app.isIosOrAndroid() == 'android') {
    //     if (new Date(this.data.time_start).getTime() >= new Date(this.data.time_end).getTime()) {
    //       wx.showToast({
    //         title: '开始时间必须早于结束时间',
    //         icon: 'none'
    //       });
    //       return;
    //     }
    //   }else {
    //     if (parseInt(Date.parse(new Date(this.data.time_start.replace(/-/g, '/')))) >= parseInt(Date.parse(new Date(this.data.time_end.replace(/-/g, '/'))))) {
    //       wx.showToast({
    //         title: '开始时间必须早于结束时间',
    //         icon: 'none'
    //       });
    //       return;
    //     }
    //   }
    // }
    if (this.data.coupon_method === 1) {
      if (app._isTextEmpty(this.data.deduct)) {
        wx.showToast({
          title: '请输入立减金额',
          icon: 'none'
        });
        return;
      }
      else if (this.data.deduct < 1) {
        wx.showToast({
          title: '金额必须大于1',
          icon: 'none'
        });
        return;
      }
      else if (this.data.deduct > this.data.enough) {
        let between = `输入的金额必须介于1-${this.enough}之间`;
        wx.showToast({
          title: between,
          icon: 'none'
        });
        return;
      }
    }
    if (this.data.coupon_method === 2) {
      if (app._isTextEmpty(this.data.discount)) {
        wx.showToast({
          title: '请输入折扣数',
          icon: 'none'
        });
        return;
      }
      else if (this.data.discount < 1 || this.data.discount > 10) {
        let Between = `折扣数必须介于1-10之间`;
        wx.showToast({
          title: Between,
          icon: 'none'
        });
        return;
      }
    }
    if (this.data.use_type === 1) {
      if (this.data.category.length <= 0) {
        wx.showToast({
          title: '分类不能为空',
          icon: 'none'
        });
        return;
      }
    }
    if (this.data.use_type === 2) {
      if (this.data.goods.length <= 0) {
        wx.showToast({
          title: '商品不能为空',
          icon: 'none'
        });
        return;
      }
    }
    if (this.data.get_type === 1) {
      if (app._isTextEmpty(this.data.get_max)) {
        wx.showToast({
          title: '请输入限领张数',
          icon: 'none'
        });
        return;
      } else if (app._isTextEmpty(this.data.total)) {
        wx.showToast({
          title: '请输入发放总数',
          icon: 'none'
        });
        return;
      }
    }
    // if (app._isTextEmpty(this.data.onceTotal)) {
    //   wx.showToast({
    //     title: '请输入每人每日限领数量',
    //     icon: 'none'
    //   });
    //   return;
    // }
    if (this.data.get_type === 0) {
      if (app._isTextEmpty(this.data.total)) {
        wx.showToast({
          title: '请输入发放总数',
          icon: 'none'
        });
        return;
      }
    }
    this.data.sendBtnFlag = true;
    let time_start = new Date(this.data.time_start.replace(/-/g, '/'));
    time_start = time_start.getTime() / 1000;
    let time_end = new Date(this.data.time_end.replace(/-/g, '/'));
    time_end = time_end.getTime() / 1000;

    let json = {
      coupon: {
        id: this.data.id,
        name: this.data.name,
        get_type: this.data.get_type,
        level_limit: this.data.level_limit,
        use_type: this.data.use_type,
        enough: this.data.enough,
        time_limit: this.data.time_limit,
        time_days: this.data.time_days,
        time_start: time_start,
        time_end: time_end,
        coupon_method: this.data.coupon_method,
        discount: this.data.discount,
        deduct: this.data.deduct,
        total: this.data.total,
        status: this.data.status,
        display_order: this.data.display_order,
        is_complex: this.data.is_complex,
        get_max: this.data.get_max,
        category: this.data.category,
        goods: this.data.goods,
        get_limit_max:this.data.onceTotal?this.data.onceTotal:0
      }
    };
    if (this.data.use_type == 1) {
      json.coupon.goods = [];
    } else if (this.data.use_type == 2) {
      json.coupon.category = [];
    }
    let urlStr = app.getNetAddresss('plugin.store-cashier.frontend.store.center.coupon.save');
    app._postNetWork({
      url: urlStr,
      data: json,

      success: (resdata) => {
        var response = resdata.data;

        if (response.result == 1) {
          wx.showToast({
            title: '保存成功'
          });
          setTimeout(() => {
            wx.navigateBack({
              delta: 1
            });
          }, 2000);
        }
        else if (response.result === 0) {
          if (response.data.url) {
            // window.location.href = response.data.url
          }else {
            if(response.msg.enough){
              wx.showToast({
                title:response.msg.deduct[0],
                icon: 'none'
              });
            }else{
              wx.showToast({
                title: response.msg ,
                icon: 'none'
              });
            }
          }
          this.data.sendBtnFlag = false;
        }
      },
      fail: (res)=> {
        this.data.sendBtnFlag = false;
        console.log(res);
      }
    });
  },
  onChange(e) {
    console.log(e,"e====")
    this.setData({
      status: e.detail
    });
  },
  onChangeData(e) {
    if (e.detail == '1') {
      let time_start = new Date(this.data.time_start);
      time_start = time_start.getTime();
      let time_end = new Date(this.data.time_end);
      time_end = time_end.getTime();
      this.setData({
        time_startTimes: time_start,
        time_endTimes: time_end
      });
    }
    this.setData({
      time_limit: e.detail
    });
  },
  onChangeNum(e) {
    this.setData({
      is_complex: e.detail
    });
  },
  onChangeAdd(e) {
    this.setData({
      coupon_method: e.detail
    });
  },
  onChangeCate(e) {
    this.setData({
      use_type: e.detail
    });
  },
  onChangeforu(e) {
    this.setData({
      get_type: e.detail
    });
  },
  onChangeLimt(e) {
    if (e.detail != '-1') {
      this.setData({
        level_limit: parseInt(e.detail)
      });
    } else {
      this.setData({
        level_limit: e.detail
      });
    }
  },
  close_category(){
    this.setData({show7:false})
  },
  onClickRange(e){
    let use_type = e.currentTarget.dataset.name;
    this.setData({use_type});
  },
  onClickUse(e){
    let is_complex = e.currentTarget.dataset.name;
    this.setData({is_complex});
  },
  onClick(e){
    let level_limit = e.currentTarget.dataset.name;
    console.log(level_limit,"level_limit=====");
    if (level_limit == '-1') {
      this.setData({
        level_limit: parseInt(level_limit),
        chooseVip: '所有会员'
      });
    } else {
      for (let i = 0;i < this.data.Vip.length;i++) {
        console.log(level_limit == this.data.Vip[i].id,this.data.Vip[i].id);
        if (level_limit == this.data.Vip[i].id) {
          this.setData({
            chooseVip: `${this.data.Vip[i].level_name}`
          });
        }
      }
      this.setData({
        level_limit
      });
    }
  },
  close_use(){
    this.setData({show6:false})
  },
  // 关闭弹窗
  onCloseShow() {
    this.setData({
      show3: false,
      show1: false,
      show2: false,
      show4: false,
      show5: false,
    });
  },
  clearSrcoll(e) {
    console.log(e.detail, '测试');

    this.setData({
      goodsKeyword: e.detail
    });
  },
  clearSrcollCate(e) {
    this.setData({
      keyword: e.detail
    });
  },
  tapshowUse(){
    this.setData({show6:true});
  },
  tapshowMember() {
    this.setData({
      show1: true
    });
  },
  clearSrcollDeduct(e) {
    this.setData({
      deduct: e.detail.value
    });
  },
  clearSrcollDis(e) {
    this.setData({
      discount: e.detail.value
    });
  },
  // 排序
  clearSrcollSort(e) {
    this.setData({
      display_order: e.detail.value
    });
  },
  // 名字
  clearSrcollName(e) {
    this.setData({
      name: e.detail.value
    });
  },
  // 金额
  clearSrcollEnough(e) {
    this.setData({
      enough: e.detail.value
    });
  },
  // 有效时间
  clearSrcollTime(e) {
    this.setData({
      time_days: e.detail.value
    });
  },
  tapIShow() {
    this.setData({
      show4: true});
  },
  tapIShowOne() {
    this.setData({
      show5: true});
  },
  onInput() {
    this.setData({
      show4: false,
      show5: false
    });
  },
  firmOnye(e) {
    if (Number.isNaN(e.detail)) {
      this.setData({
        show4: false,
        time_start: '2017-05-11'
      });
      return;
    }
    let times = this.format(e.detail);
    this.setData({
      show4: false,
      time_start: times,
      time_startTimes: e.detail
    });
  },
  // 发布
  firmOnyeOpios(e) {
    if (e.detail == 'NaN') {
      this.setData({
        show5: false,
        time_end: '2017-05-11'
      });
      return;
    }
    let times = this.format(e.detail);
    this.setData({
      show5: false,
      time_end: times,
      time_endTimes: e.detail
    });
  },
  clearSrcollGetMax(e) {
    this.setData({
      get_max: e.detail.value
    });
  },
  clearSrcollTotal(e) {
    this.setData({
      total: e.detail.value
    });
  },
  clearSrcollonceTotal(e){
    console.log(e,"e===");
    this.setData({
      onceTotal: e.detail.value
    });
  },
  // 转换格式
  add0(m) {return m < 10 ? '0' + m : m; },
  format(shijianchuo) {
    // shijianchuo是整数，否则要parseInt转换
    var time = new Date(parseInt(shijianchuo));
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    // var s = time.getSeconds();
    return y + '-' + this.add0(m) + '-' + this.add0(d);
  },
  toggle_goods(event){
    const { index } = event.currentTarget.dataset;
    const checkbox = this.selectComponent(`.checkboxes_goods-${index}`);
    checkbox.toggle();
  },
  toggle(event) {
    const { index } = event.currentTarget.dataset;
    const checkbox = this.selectComponent(`.checkboxes-${index}`);
    checkbox.toggle();
  },
  onchangeGroup(e) {
    this.setData({
      fenleiSelect: e.detail
    });
    console.log(this.data.Id,'e.detail',e.detail)
    if(this.data.Id=='abc'){
      let newArr =this.data.fenleiSelect;
      let oldArr = this.data.sousuoInfoAllOIs;
      let arrIOs = this.data.fenleirange;
      oldArr.map(item => {
        for (var i = 0; i < newArr.length; i++) {
          if (item.id == newArr[i]) {
            arrIOs.push(item);
          }
        }
      });
      let _fenleirange =  this.filter_utils(arrIOs);
      this.setData({fenleirange: _fenleirange});
    }else{
      let arrAll = this.data.sousuoInfoSearch;
      let arrChe = this.data.fenleiSelect;
      let arrNow = this.data.category;
      arrAll.map(item => {
        for (var i = 0; i < arrChe.length; i++) {
          console.log(item.id==arrChe[i],item.name,'item.name',arrChe[i],'arrChe[i]');
          if (item.id == arrChe[i]) {
            arrNow.push(item);
          }
        }
      });
      let _category =  this.filter_utils(arrNow);
      this.setData({
        category:_category
      });
    }
  },
  filter_utils(arr){
    return arr.filter((item,index, arr) => {
      return arr.indexOf(item) === index
    })
  },
  onchangeSelect(e) {
    let goodsSelect = e.detail;
    this.setData({goodsSelect});
    if(this.data.Id=='abc'){
      let goodsrange = this.data.goodsrange;
      this.data.goodsSousuo.map(item => {
        for (var i = 0; i < goodsSelect.length; i++) {
          if (item.id == goodsSelect[i]) {
            goodsrange.push(item);
          }
        }
      });
      let _goodsrange=  this.filter_utils(goodsrange);
      this.setData({goodsrange:_goodsrange});
    }else{
      let goods = this.data.goods;
      this.data.goodsSousuoAll.map(item => {
        for (var i = 0; i < goodsSelect.length; i++) {
          console.log(item.id == goodsSelect[i],item.id,goodsSelect[i]);
          if (item.id == goodsSelect[i]) {
            goods.push(item);
          }
        }
      });
      
      let _goods=  this.filter_utils(goods);
      this.setData({goods:_goods});
    }
  }
});
